package org.stool.netty.http.download;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.LastHttpContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;

public class Downloader {

    private Connector connector = new Connector();

    private final static Logger LOG = LoggerFactory.getLogger(Downloader.class);

    public void download(String url, String localFilePath) {

        URI uri;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return ;
        }

        try {
            final File file = new File(localFilePath);
            if(!file.exists()){
                file.createNewFile();
            }

            final OutputStream out = new FileOutputStream(file);


            Handler<Throwable> connectFailHandler = t -> {
                LOG.error("connect fail", t);
            };

            Handler<HttpResponse> responseHandler = response -> {
                LOG.error("status is not ok", response.status().toString());
            };

            Handler<HttpContent> messageHandler = content -> {

                try {
                    ByteBuf byteBuf = content.content();
                    if (byteBuf.isDirect()) {
                        byteBuf = Unpooled.copiedBuffer(byteBuf);
                    }
                    out.write(byteBuf.array());

                    if (content instanceof LastHttpContent) {
                        out.flush();
                        out.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            };

            connector.connect(uri.getHost(), uri.getPort() == -1 ? 80 : uri.getPort(), uri.getPath(), connectFailHandler, responseHandler, messageHandler);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new Downloader().download("http://apache.communilink.net/tomcat/tomcat-7/v7.0.92/bin/apache-tomcat-7.0.92.zip", "./file.zip");
    }

}
